<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>04_深拷贝和浅拷贝-其他类型</title>
</head>

<body>

  <script>
    function isObject(value) {
      const valueType = typeof value
      return (value !== null) && (valueType === 'object' || valueType === 'function')
    }
  </script>
  <script>
    function deepClone(origin) {
      // Symbol类型
      if (typeof origin === 'symbol') {
        return Symbol(origin.description)
      }

      // 函数类型
      if (typeof origin === 'function') {
        return origin
      }

      // RegExp类型
      if (origin instanceof RegExp) {
        return new RegExp(origin.source, origin.flags)
      }

      // Date类型
      if (origin instanceof Date) {
        return new Date(origin)
      }

      if (!isObject(origin)) return origin

      // set类型
      if (origin instanceof Set) {
        // return new Set([...origin])
        const newSet = new Set()
        for (const item of origin) {
          newSet.add(deepClone(item))
        }
        return newSet
      }

      const newObj = Array.isArray(origin) ? [] : {}
      for (const key in origin) {
        newObj[key] = deepClone(origin[key])
      }
      return newObj
    }

    const set = new Set(["abc", "cba", "nba"])
    const s1 = Symbol("s1")
    const s2 = Symbol("s2")
    const obj = {
      name: "deepClone",
      age: 18,
      address: {
        city: "北京",
        home: {
          name: "home"
        }
      },
      arr: [1, 2, 3],

      // 1.特殊类型: Set
      set: set,

      // 2.特性类型: function
      running: function() {
        console.log("running~")
      },

      // 3.值的特殊类型: Symbol
      symbolKey: Symbol("abc"),

      // 4.key是symbol时
      [s1]: "aaaa",
      [s2]: "bbbb"
    }

    const newObj = deepClone(obj)
    obj.arr[1] = 100
    console.log(obj, newObj);
    console.log(set instanceof Set, isObject(s2));
    
    
    
  </script>

</body>

</html>